/*********************************************************
          File Name:sendfd.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Wed 01 Jul 2015 09:47:17 AM CST
**********************************************************/

#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <time.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include "sendfd.h"

int sndsockfd(int pair, int sendfd)
{
    struct msghdr msg;
    struct iovec iov[1];
    char ptr[256] = {0};
    int ptrlen = 256;

#ifndef HAVE_MSGHDR_MSG_CONTROL
    union {
            struct cmsghdr cm;
            char control[CMSG_SPACE(sizeof(int))];
    } control_un;

    struct cmsghdr *cmptr;

    msg.msg_control = control_un.control;
    msg.msg_controllen = sizeof(control_un.control);

    cmptr = CMSG_FIRSTHDR(&msg);
    cmptr->cmsg_len = CMSG_LEN(sizeof(int));
    cmptr->cmsg_level = SOL_SOCKET;
    cmptr->cmsg_type = SCM_RIGHTS;
    *((int *) CMSG_DATA(cmptr)) = sendfd;
#else
    msg.msg_accrights = (caddrt_t)&sendfd);
    msg.msg_accrightslen = sizeof(int);
#endif

    msg.msg_name = NULL;
    msg.msg_namelen = 0;

    iov[0].iov_base = ptr;
    iov[0].iov_len = ptrlen;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    return (sendmsg(pair, &msg, 0));
}

int rcvsockfd(int pair)
{
        struct msghdr msg;
        struct iovec iov[1];
        ssize_t n;
        int newfd;
        char ptr[256] = {0};
        int ptrlen = 256;

#ifndef HAVE_MSGHDR_MSG_CONTROL
    union {
            struct cmsghdr cm;
            char control[CMSG_SPACE(sizeof(int))];
    } control_un;

    struct cmsghdr *cmptr;

    msg.msg_control = control_un.control;
    msg.msg_controllen = sizeof(control_un.control);
#else
    msg.msg_accrights = (caddr_t)&newfd;
    msg.nsg_namelen = sizeof(int);
#endif

    msg.msg_name = NULL;
    msg.msg_namelen = 0;

    iov[0].iov_base = ptr;
    iov[0].iov_len = ptrlen;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;

    if((n = recvmsg(pair, &msg, 0)) <= 0)
            return n;

#ifndef HAVE_MSGHDR_MSG_CONTROL
    if((cmptr = CMSG_FIRSTHDR(&msg)) != NULL &&
        cmptr->cmsg_len == CMSG_LEN(sizeof(int)))
    {
            if(cmptr->cmsg_level != SOL_SOCKET)
                    return -1;
            if(cmptr->cmsg_type != SCM_RIGHTS)
                    return -1;
            newfd = *((int *) CMSG_DATA(cmptr));
            return newfd;
    }
    else
            return -1;
#else
    if(msg.msg_accrightslen == sizeof(int))
            return newfd;
    else
            return -1;
#endif
}
